<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-05 09:08:10
 * @LastEditors: william
 * @LastEditTime: 2025-06-18 10:39:32
-->
<template>
  <el-date-picker
    v-model="dateTimeValue"
    class="nw-date-picker"
    :type="type"
    :clearable="clearable"
    :start-placeholder="$t('public.startDate')"
    :range-separator="$t('public.to')"
    :end-placeholder="$t('public.endDate')"
    :placeholder="$t('public.selectTimePeriod')"
    format="YYYY-MM-DD HH:mm:ss"
    value-format="YYYY-MM-DD HH:mm:ss"
    :default-time="defaultTime"
    :disabled-date="disabledDate"
    :shortcuts="pickerType === '1' ? [] : shortcuts1"
    :="$attrs"
    @calendar-change="calendarChange"
    @clear="calendarClear"
  />
</template>

<script setup>
const props = defineProps({
  type: {
    type: String,
    default: 'datetimerange' // datetimerange/daterange
  },
  clearable: {
    type: Boolean,
    default: true
  },
  maxTime: {
    type: [String, Object],
    default: ''
  },
  timeRange: {
    type: Number,
    default: 7 // 可最大选择时间范围的区间,包括当天 30/7
  },
  pickerType: {
    type: String,
    default: '1' // 1-没有快捷选项，2-有最近一周/最近一个月的快捷选项
  }
})

const dateTimeValue = defineModel({
  type: Array,
  default: []
})
const defaultTime = [
  new Date(2025, 1, 1, 0, 0, 0),
  new Date(2025, 1, 1, 23, 59, 59)
] // ['00:00:00', '23:59:59']

const firstChooseDate = ref('')

const disabledDate = time => {
  const todayMaxTime = props.maxTime
    ? new Date(props.maxTime).getTime()
    : Date.now()
  if (firstChooseDate.value) {
    const timeRange = (props.timeRange - 1) * 24 * 3600 * 1000
    const minTime = firstChooseDate.value - timeRange
    let maxTime = firstChooseDate.value + timeRange
    if (maxTime > todayMaxTime) maxTime = todayMaxTime
    return time.getTime() < minTime || time.getTime() > maxTime
  } else {
    return time.getTime() > todayMaxTime
  }
}

// 有最近一周/最近一个月的快捷选项
const shortcuts1 = [
  {
    text: g_t('public.nearestWeek'),
    value: _ => {
      const start = g_dayjs().subtract(6, 'day').startOf('day').valueOf()
      const end = g_dayjs().endOf('day').valueOf()
      return [start, end]
    }
  },
  {
    text: g_t('public.nearestMonth'),
    value: _ => {
      const start = g_dayjs()
        .subtract(1, 'month')
        .add(1, 'day')
        .startOf('day')
        .valueOf()
      const end = g_dayjs().endOf('day').valueOf()
      return [start, end]
    }
  }
]

const calendarChange = val => {
  firstChooseDate.value = val[0].getTime() // 点击第一次选中日期
  if (val[1]) firstChooseDate.value = '' // 选中后必须清空
}

const calendarClear = _ => {
  dateTimeValue.value = []
}
</script>

<style lang="scss">
#app .nw-date-picker,
.nw-dialog .nw-date-picker {
  width: 100%;
  min-width: 250px;
  max-width: 380px;
}
</style>
